import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/comment_view_logic.dart';
import 'package:ball_lion/module/home/news_detail_logic.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class CommentInputSheet extends StatefulWidget {
  const CommentInputSheet({
    super.key,
    required this.focusNode,
    required this.textEditingController,
    required this.textId,
    required this.hintText,
    required this.sndAction,
  });

  final FocusNode focusNode;
  final TextEditingController textEditingController;
  final String textId;
  final String hintText;
  final void Function(String text) sndAction;

  @override
  State<CommentInputSheet> createState() => _CommentInputSheetState();
}

class _CommentInputSheetState extends State<CommentInputSheet> {
  doSndText() {
    Get.back();
    widget.sndAction.call(widget.textEditingController.text);
  }

  @override
  void initState() {
    super.initState();
    Get.find<ConfigService>().tipEnable = false;
    widget.textEditingController.text =
        CommentInputWidget.storedTexts[widget.textId] ?? "";
    Future.delayed(const Duration(milliseconds: 100)).then((value) {
      widget.focusNode.requestFocus();
      update();
    });
  }

  @override
  void dispose() {
    Get.find<ConfigService>().tipEnable = true;
    CommentInputWidget.storedTexts[widget.textId] =
        widget.textEditingController.text;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheet(
      backgroundColor: Colors.transparent,
      enableDrag: false,
      onClosing: () {},
      builder: (context) {
        return Column(
          children: [
            Expanded(
                child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () => Get.back(),
              onPanStart: (details) => Get.back(),
            )),
            content
          ],
        );
      },
    );
  }

  Widget get content => Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
        decoration: const BoxDecoration(
            color: Colors.white,
            border:
                Border(top: BorderSide(color: Color(0xffeeeeee), width: 0.5))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [Expanded(child: _inputWidget()), _sndButton()],
        ),
      );

  Widget _sndButton() => () {
        final dosnd = widget.textEditingController.text.isNotEmpty;
        return QsText(dosnd ? '发送' : '发布',
                needCenter: true,
                fontWeight: FontWeight.w500,
                color: dosnd ? Colours.main : Colours.grey99)
            .paddingOnly(left: 10, bottom: 6, top: 6)
            .tap(() => doSndText());
      }.call();

  Widget _inputWidget() => Container(
        decoration: BoxDecoration(
            color: const Color(0xFFF2F2F2),
            borderRadius: BorderRadius.circular(6)),
        child: CupertinoTextField(
          maxLines: 4,
          minLines: 1,
          controller: widget.textEditingController,
          focusNode: widget.focusNode,
          maxLength: 200,
          onChanged: (value) {
            update();
            if (value.characters.length == 200) {
              Toast.text("评论最多输入200字");
            }
          },
          cursorColor: Colours.main,
          textInputAction: TextInputAction.send,
          prefix: Image.asset(Utils.getImgPath("comment_pencil.png"))
              .marginOnly(left: 12),
          prefixMode: OverlayVisibilityMode.never,
          placeholder: widget.hintText,
          // strutStyle: Styles.centerStyle(fontSize: 12),
          placeholderStyle:
              const TextStyle(fontSize: 14, color: Colours.grey99, height: 1.3),
          onSubmitted: (value) {
            doSndText();
          },
          decoration: const BoxDecoration(color: Colors.transparent),
        ),
      );
}

class CommentInputWidget extends StatefulWidget {
  const CommentInputWidget(
      {super.key,
      this.clickSnd,
      this.textEditingController,
      this.focusNode,
      this.news,
      this.cid,
      this.hintText,
      this.commentNum,
      required this.textId,
      required this.newsId,
      this.onInit,
      this.canInput,
      this.numberBtn = true,
      this.afterShare});

  final FutureOr<bool?> Function(String text)? clickSnd;
  final TextEditingController? textEditingController;
  final FocusNode? focusNode;
  // final bool inNewsPage;
  final NewsItemEntity? news;
  final int? cid;
  final String? hintText;
  final String textId;
  final int newsId;
  final int? commentNum;
  final bool Function(bool isbtn)? canInput;
  final bool numberBtn;
  final void Function()? afterShare;

  final void Function(FutureOr Function() doFocus)? onInit;

  static Map<String, String> storedTexts = {};

  @override
  State<CommentInputWidget> createState() => _CommentInputWidgetState();
}

class _CommentInputWidgetState extends State<CommentInputWidget> {
  final _tec = TextEditingController();
  final _focus = FocusNode();
  TextEditingController get tec => widget.textEditingController ?? _tec;
  FocusNode get focus => widget.focusNode ?? _focus;
  bool editing = false;
  // bool get isLike => widget.news?.isLike == 1;
  // int? get commentNum => widget.commentNum ?? widget.news?.commentNum;
  late CommentViewLogic logic;
  late NewsDetailLogic newsLogic;

  @override
  void initState() {
    super.initState();
    logic = Get.find<CommentViewLogic>(tag: '${widget.newsId}');
    newsLogic = Get.find<NewsDetailLogic>(tag: '${widget.newsId}');
    widget.onInit?.call(() async {
      await toInput(false);
    });
  }

  @override
  void dispose() {
    _tec.dispose();
    _focus.dispose();
    super.dispose();
  }

  _doSndAction() async {
    User.needLogin(() async {
      if (focus.hasFocus) {
        focus.unfocus();
        final text = tec.text.trim();
        if (text.isEmpty) {
          return;
        }
        final r =
            await widget.clickSnd?.call(text) ?? await logic.doSndComment(text);
        // if (r) {
        tec.text = "";
        CommentInputWidget.storedTexts[widget.textId] = "";
        // }
      } else {
        focus.requestFocus();
      }
    });
  }

  bool inputing = false;
  toInput(bool isbtn) async {
    if (inputing) {
      return;
    }
    if (!(widget.canInput?.call(isbtn) ?? true)) {
      return;
    }
    inputing = true;
    update();
    await Get.bottomSheet(
        CommentInputSheet(
          focusNode: focus,
          textEditingController: tec,
          textId: widget.textId,
          hintText: widget.hintText ?? "友善评论",
          sndAction: (text) {
            focus.unfocus();
            _doSndAction();
          },
        ),
        backgroundColor: Colors.transparent,
        barrierColor: Colors.transparent,
        enableDrag: false);
    inputing = false;
    update();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
      height: 44,
      decoration: const BoxDecoration(
          border:
              Border(top: BorderSide(color: Color(0xffeeeeee), width: 0.5))),
      child: Row(
        crossAxisAlignment: (!editing && widget.news != null)
            ? CrossAxisAlignment.center
            : CrossAxisAlignment.end,
        children: [
          Expanded(child: _inputWidget()),
          if (!editing && widget.news != null) _btns(),
          if (editing || widget.news == null) _sndButton()
        ],
      ),
    );
  }

  Widget _btns() => Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(width: 24),
          GestureDetector(
            onTap: () {
              Utils.onEvent("zxxq", params: {"zxxq": 5});
              newsLogic.onZan();
            },
            child: Row(
              children: [
                Image.asset(
                  Utils.getImgPath(
                      newsLogic.data?.isLike == 1 ? 'zan_red.png' : 'zan.png'),
                  width: 22,
                ),
                const SizedBox(width: 6),
                SizedBox(
                    width: 40,
                    child: QsText(
                        newsLogic.data?.likeNum.hasValue == true
                            ? '${newsLogic.data?.likeNum}'
                            : '赞',
                        fontSize: 13,
                        color: newsLogic.data?.isLike == 1
                            ? Colours.main
                            : Colours.text))
              ],
            ),
          ),
          GestureDetector(
            onTap: () {
              toInput(true);
            },
            child: Row(
              children: [
                Image.asset(
                  Utils.getImgPath('comment.png'),
                  width: 22,
                ),
                const SizedBox(width: 6),
                SizedBox(
                    width: 40,
                    child: QsText(
                        newsLogic.data?.commentNum.hasValue ?? false
                            ? '${newsLogic.data?.commentNum}'
                            : '评',
                        fontSize: 13))
              ],
            ),
          ),
          Image.asset(
                  Utils.getImgPath(newsLogic.data?.collectId == 0
                      ? "collection.png"
                      : "collection_red.png"),
                  width: 22,
                  height: 22)
              .tap(() async {
            // final news = widget.news;
            // if (news == null) {
            //   return;
            // }
            // if (widget.news?.collectId != null) {
            //   final result = await UserApi.deleteCollect(widget.news!.id!);
            //   if (result == 200) {
            //     widget.news?.collectId = null;
            //   }
            // } else {
            //   final result =
            //       await UserApi.collect(news.type ?? 1, news.id ?? 0);
            //   if (result == 200) {
            //     widget.news?.collectId = 0;
            //   }
            // }
            // update();
            newsLogic.onCollect();
          }),
        ],
      ).sized(height: 44);

  Widget _sndButton() =>
      QsText('发布', fontWeight: FontWeight.w500, color: Colours.grey99)
          .paddingOnly(left: 10, bottom: 6, top: 6)
          .tap(() => toInput(false));

  Widget _inputWidget() => Container(
        decoration: BoxDecoration(
            color: const Color(0xFFF2F2F2),
            borderRadius:
                editing ? BorderRadius.circular(6) : BorderRadius.circular(30)),
        height: 32,
        child: CupertinoTextField(
          onTap: () {
            Utils.onEvent("zxxq", params: {"zxxq": 6});
            toInput(false);
          },
          readOnly: true,
          prefix: Image.asset(
            Utils.getImgPath("comment_pencil.png"),
            width: 14,
            height: 14,
          ).marginOnly(left: 12),
          prefixMode: OverlayVisibilityMode.notEditing,
          placeholder: "友善评论",
          placeholderStyle:
              const TextStyle(fontSize: 14, color: Colours.grey99),
          decoration: const BoxDecoration(color: Colors.transparent),
        ),
      );
}
